<?php
namespace app\admin\controller;
use think\Controller;

Class Brand extends BaseAdmin
{

	//品牌列表
    public function lst()
    {
    	
        
        $BrandRes=db('tp_brand')->paginate(3);
        $this->assign('BrandRes',$BrandRes);
        // dump($data->render());
        // exit;
        return $this->fetch('list');
    }

    //品牌添加
    public function add()
    {
    	 
        if(request()->isPost()){
        	$data=input('post.');
        	if($data['brand_url']&&stripos($data['brand_url'],'http://')===false){
        		$data['brand_url']='http://'.$data['brand_url'];
        	}

        	if($_FILES['brand_img']['tmp_name']){
        		$data['brand_img']=$this->upload();
        	}


        	//验证
        	$validate = new \app\admin\validate\Brand;
        	if (!$validate->check($data)) {
        		$this->error($validate->getError());
        	}
        	
        	$add=db('tp_brand')->insert($data);
        	if($add){
        		$this->success('保存成功','lst');
        	}
        	else{
        		$this->error('保存失败');
        	}

        }
        return $this->fetch();

    }

    //品牌编辑
    public function edit($id)
    {
    	$BrandRes=db('tp_brand')->where(array('id'=>$id))->find();
    	$this->assign('BrandRes',$BrandRes);
    	if(request()->isPost()){
        	$data=input('post.');
            // dump($_FILES);die;
        	if($data['brand_url']&&stripos($data['brand_url'],'http://')===false){
        		$data['brand_url']='http://'.$data['brand_url'];
        	}

        	if($_FILES['brand_img']['tmp_name']){
                $oldBrandImg=IMG_UPLOADS.$BrandRes['brand_img'];
                if(file_exists($oldBrandImg)){
                    @unlink($oldBrandImg);
                }
        		$data['brand_img']=$this->upload();
        	}
        	$up=db('tp_brand')->where(array('id'=>$id))->update($data);
        	// dump($up);
        	// exit;
        	if($up!==false){
        		$this->success('保存成功','lst');
        	}
        	else{
        		$this->error('保存失败');
        	}

        }
        return $this->fetch();
    }

    //品牌删除
    public function del($id)
    {
    	$del=db('tp_brand')->delete($id);
    	if($del){
    		$this->success('删除成功','lst');

    	}else{
            $this->error('删除失败');
    	}
    	
        return $this->fetch();
    }

    
    //图片上传
	public function upload(){
		$file=request()->file('brand_img');
		if($file==null){
			exit(json_encode(array('msg'=>'没有文件上传')));
		}
		$info=$file->move('../public/static/uploads');
		$ext=$info->getExtension();//获取后缀名
		if(!in_array($ext,array('jpg','png','gif','jpeg'))){
			exit(json_encode(array('msg'=>'文件格式不符合')));
		}
		if($info){
			return $img=$info->getSaveName();

		}else{
			$file->getError();
			die;
		}
		
		
	}


}